<template>
    <el-container class="stock_goods_container">
        <!--物料类目组件-->
        <CategoryTree ref="refCategoryTree" title="物料类目" detail
                      @event="handleTreeEvent"/>
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="searchForm"
                                @event="handleHeaderEvent">
                    <template slot="right_search">
                        <el-select v-model="searchForm.warehouse_sid" placeholder="全部仓库"
                                   class="w100" clearable @change="getList(true)"
                                   style="margin-right: 5px;">
                            <el-option label="全部仓库" value=""/>
                            <el-option v-for="(item, index) in warehouseList"
                                       :key="index" :label="item.label" :value="item.value"/>
                        </el-select>
                        <el-form-item label="物料编号" class="right_search_query">
                            <el-input v-model="searchForm.goods_code" style="width: 168px" @change="getList(true)"
                                      clearable/>
                        </el-form-item>
                        <el-form-item label="物料名称" class="right_search_query">
                            <el-input v-model="searchForm.goods_name" style="width: 168px" @change="getList(true)"
                                      clearable/>
                        </el-form-item>
                    </template>
                </headerTemplate>
                <vxeTableTemplate ref="stockGoodsTableRef" :data="dataList" :options.sync="tableOptions"
                                  @event="handleTableEvent"/>
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import {mapState} from "vuex";
import poiApi from "@common/api/poiApi";
import clothing from "@jxc/utils/clothing";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "JxcStockGoods",
    components: {
        CategoryTree: () => import('../../components/CategoryTree.vue'),
    },
    data() {
        let _this = this;
        return {
            currentNode: [],
            treeNodeKey: {},
            headerOption: {
                toolbar_buttons: [
                    {
                        id: 'refresh',
                        icon: 'el-icon-refresh-right',
                        show: true,
                        method: () => {
                            _this.getList(true);
                        },
                    },
                    {
                        id: 'import',
                        label: '更新库存',
                        icon: 'el-icon-top',
                        type: 'primary',
                        show: true,
                        method: () => {
                            _this.openImportDialog();
                        },
                    },
                ],
                toolbar_filter: [],
            },
            searchForm: {
                warehouse_sid: '',
            },
            warehouseList: [],
            dataList: [],
            tableOptions: {
                ref: "stockGoodsTable",
                container: ".stock_goods_container",
                columns: [],
                baseColumns: [
                    {
                        label: '仓库名称',
                        prop: 'warehouse_name',
                        align: 'center',
                        minWidth: 100,
                        exportMinWidth: 20,
                    },
                    {
                        label: '物料类目',
                        prop: 'category_name',
                        align: 'center',
                        exportMinWidth: 20,
                    },
                    {
                        label: '物料编号',
                        prop: 'goods_code',
                        align: 'center',
                        exportMinWidth: 20,
                    },
                    {
                        label: '物料名称',
                        prop: 'goods_name',
                        align: 'center',
                        exportMinWidth: 30,
                    },
                    {
                        label: '规格',
                        prop: 'goods_spec',
                        align: 'center',
                        exportMinWidth: 20,
                    },
                    {
                        label: '型号',
                        prop: 'goods_model',
                        align: 'center',
                        exportMinWidth: 20,
                    },
                    {
                        label: '计量单位',
                        prop: 'base_unit',
                        align: 'center',
                        width: 80,
                        exportMinWidth: 20,
                    },
                    {
                        label: '平均采购价',
                        prop: 'avg_cost',
                        align: 'center',
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4),
                        exportMinWidth: 15,
                        isAmount: true,
                        exportDataFormat: '#,##0.0000',
                    },
                    {
                        label: '初始库存数量',
                        prop: 'init_qty',
                        align: 'center',
                        minWidth: 100,
                        exportMinWidth: 20,
                        isAmount: true,
                        exportDataFormat: '#,##0.000',
                    },
                    {
                        label: '库存数量',
                        prop: 'stock_sum_qty',
                        align: 'center',
                        minWidth: 100,
                        exportMinWidth: 20,
                        isAmount: true,
                        exportDataFormat: '#,##0.000',
                        export: false,
                    },
                    {
                        label: '库存金额',
                        prop: 'stock_sum_amount',
                        align: 'center',
                        minWidth: 100,
                        exportMinWidth: 20,
                        isAmount: true,
                        exportDataFormat: '#,##0.0000',
                        export: false,
                    },
                    {
                        label: '物料图标',
                        prop: 'goods_pic_file_sid',
                        align: 'center',
                        cellRender: {
                            name: 'TableImage',
                        },
                        export: false,
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: "detail",
                            icon: "fa fa-info-circle",
                            type: "warning",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "购销清单",
                            },
                            method: (index, row) => {
                                _this.jumpRoute('/jxcBuySaleBillDetailReport', {
                                    goods_sid: row.goods_sid,
                                });
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
        };
    },
    computed: {
        ...mapState('jxc', ['setting']),
    },
    mounted() {
        this.init();
    },
    methods: {
        async init() {
            const _this = this;
            await _this.storeDispatch('jxc/initSetting');
            await _this.initWarehouseList();
            _this.initTableOptions();
            _this.getList(true);
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = clothing.resetTableColumns(_this.setting, columns, 'stock_sum_qty');
            columns = columns.map(item => {
                let obj = $.extend({}, item);
                if (obj.prop === 'clothing_color_name') {
                    obj.width = 100;
                    delete obj.render;
                }
                delete obj.editRender;
                return obj;
            });
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns,
                showSummary: true,
                summaryArray: clothing.getPresetQtyField(columns).concat(['stock_sum_qty']),
            });
        },
        handleTreeEvent(event) {
            let _this = this;
            if (['all', 'refresh'].indexOf(event.type) !== -1) {
                _this.treeNodeKey = event.data || {};
                _this.getList(true);
                return;
            }
            _this.currentNode = event.node;
            if (event.type === "nodeClick") {
                _this.treeNodeKey = event.data;
                _this.getList(true);
            }
        },
        // 刷新、查询
        handleHeaderEvent(event) {
            let _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        initWarehouseList() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindJxcStockWarehouses, {
                nopage: '1',
            }).then(res => {
                _this.warehouseList = (res.data || []).map(item => {
                    return {
                        value: item.sid,
                        label: item.name,
                    }
                });
            }).catch(() => {
            });
        },
        getListQueryData() {
            const _this = this;
            const queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            if (_this.treeNodeKey && _this.treeNodeKey.sid) {
                queryData.category_full_code = _this.treeNodeKey.full_code;
            }
            return queryData;
        },
        // 获取列表信息
        getList(query) {
            const _this = this;
            if (query) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getListQueryData();
            _this.fetchData(_this.$api.API_FindJxcStockGoodss, queryData).then(result => {
                _this.dataList = clothing.transferDetailList(_this.setting, result.data, _this.tableOptions.columns);
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
            }
        },
        openImportDialog() {
            const _this = this;
            _this.$ImportExcel({
                title: '更新库存',
                configFile: _this.$api.IMPORT_CONFIG_FILE_JXC_STOCK_GOODS,
                downloadTemplate: _this.downloadTemplate,
                uploadedShowData: true,
                event(event) {
                },
                // 点击导入按钮执行方法
                importMethod(list, dialog, formData) {
                    list = _this.resetIndex(list, 'index');
                    _this.handleImportData(list, dialog, formData);
                },
            });
        },
        downloadTemplate() {
            const _this = this;
            let queryData = _this.getListQueryData();
            queryData.template = '1';
            if (this.$refs.stockGoodsTableRef) {
                this.$refs.stockGoodsTableRef.exportTable({
                    url: _this.$api.getApiUrl(_this.$api.API_FindJxcStockGoodss),
                    param: queryData,
                    firstDataRow: 1,
                    titleField(list) {
                        const dataList = [{name: 'sid', value: 'sid'}].concat(list);
                        dataList.push({
                            name: '初始金额',
                            value: 'init_amount',
                            titleBold: '1',
                            minWidth: 20,
                            amount: '1',
                            dataFormat: '#,##0.00',
                        });
                        return dataList.map(item => {
                            const obj = $.extend({}, item);
                            if (item.value === '_index') {
                                obj.value = 'index';
                                obj.formula = '1';
                            }
                            if (item.value === 'avg_cost') {
                                obj.value = 'formula_avg_cost';
                            }
                            return obj;
                        });
                    },
                    hiddenColumn: [0],
                    lockColumn: {
                        area: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
                        bg: {
                            red: 245, green: 247, blue: 250,
                        },
                    },
                }, '物料库存模板');
            }
        },
        handleImportData(list, dialog) {
            const _this = this;
            if (!_this.$utils.isNotEmptyList(list)) {
                _this.$message.error('导入数据为空');
                return;
            }
            _this.fetchData(_this.$api.API_BatchImportStockGoods, {
                list,
            }).then(res => {
                if (_this.$utils.isNotEmpty(res.message)) {
                    _this.$message.warning(res.message);
                } else {
                    _this.$message.success('导入成功');
                }
                dialog.visible = false;
                _this.getList(true);
            }).catch(() => {
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.stock_goods_container {
    /deep/ .el-image-viewer__close {
        top: 40px;
        right: 40px;
        width: 40px;
        height: 40px;
        font-size: 40px;
        color: #FFFFFF;
    }

    .right_search_query {
        margin-top: 4px;
        margin-bottom: 4px;
    }
}
</style>
